/**
 * Copyright &copy; 2019-2022 <a href="https://gitee.com/rit/zx-pm">zx-pm</a> All rights reserved.
 */
package com.zx.pm.modules.zx.web;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zx.pm.common.beanvalidator.BeanValidators;
import com.zx.pm.common.config.Global;
import com.zx.pm.common.persistence.Page;
import com.zx.pm.common.utils.StringUtils;
import com.zx.pm.common.utils.excel.ImportExcel;
import com.zx.pm.common.web.BaseController;
import com.zx.pm.modules.zx.entity.ExpertsInfo;
import com.zx.pm.modules.zx.service.ExpertsInfoService;

/**
 * 评审专家信息管理Controller
 * @author forest
 * @version 2019-01-24
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/expertsInfo")
public class ExpertsInfoController extends BaseController {

	@Autowired
	private ExpertsInfoService expertsInfoService;
	
	@ModelAttribute
	public ExpertsInfo get(@RequestParam(required=false) String id) {
		ExpertsInfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = expertsInfoService.get(id);
		}
		if (entity == null){
			entity = new ExpertsInfo();
		}
		return entity;
	}
	
	@RequiresPermissions("zx:experts:view")
	@RequestMapping(value = {"list", ""})
	public String list(ExpertsInfo expertsInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ExpertsInfo> page = expertsInfoService.findPage(new Page<ExpertsInfo>(request, response), expertsInfo); 
		model.addAttribute("page", page);
		return "modules/zx/expertsInfoList";
	}

	@RequiresPermissions("zx:experts:view")
	@RequestMapping(value = "form")
	public String form(ExpertsInfo expertsInfo, Model model) {
		model.addAttribute("expertsInfo", expertsInfo);
		return "modules/zx/expertsInfoForm";
	}

	@RequiresPermissions("zx:experts:edit")
	@RequestMapping(value = "save")
	public String save(ExpertsInfo expertsInfo, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, expertsInfo)){
			return form(expertsInfo, model);
		}
		if (expertsInfo.getIsNewRecord()){
			if(expertsInfoService.expertsExist(expertsInfo) > 0) {
				addMessage(redirectAttributes, "评审专家信息已存在，请勿重复添加");
				return "redirect:"+Global.getAdminPath()+"/zx/expertsInfo/?repage";
			}
		}
		expertsInfoService.save(expertsInfo);
		addMessage(redirectAttributes, "保存评审专家信息成功");
		return "redirect:"+Global.getAdminPath()+"/zx/expertsInfo/?repage";
	}
	
	@RequiresPermissions("zx:experts:edit")
	@RequestMapping(value = "delete")
	public String delete(ExpertsInfo expertsInfo, RedirectAttributes redirectAttributes) {
		expertsInfoService.delete(expertsInfo);
		addMessage(redirectAttributes, "删除评审专家信息成功");
		return "redirect:"+Global.getAdminPath()+"/zx/expertsInfo/?repage";
	}

	
	@RequestMapping(value = "expertIsExist")
	@ResponseBody
	public String expertIsExist(HttpServletRequest request) {
		ExpertsInfo e = new ExpertsInfo();
		e.setCard(request.getParameter("card"));
		return expertsInfoService.expertsExist(e) > 0 ? "false" : "true";
	}
	
	@RequestMapping(value = "phoneIsExist")
	@ResponseBody
	public String phoneIsExist(HttpServletRequest request) {
		ExpertsInfo e = new ExpertsInfo();
		e.setPhone(request.getParameter("phone"));
		e.setName(request.getParameter("name"));
		return expertsInfoService.phoneIsExist(e) > 0 ? "false" : "true";
	}
	
	@RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ExpertsInfo> list = ei.getDataList(ExpertsInfo.class);
			for (ExpertsInfo expertsInfo : list){
				try{
					ExpertsInfo e = expertsInfoService.getExpertsInfo(expertsInfo.getCard());
					if(e != null){
						failureMsg.append("<br/>专家  "+expertsInfo.getName()+" 已存在; ");
						failureNum++;
					}else{
						expertsInfoService.save(expertsInfo);
						successNum++;
					}
					
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>专家 "+expertsInfo+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>专家 "+expertsInfo.getName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条专家信息，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条专家信息"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/zx/expertsInfo/?repage";
    }
	
	@RequestMapping(value = "import/template", method = RequestMethod.GET)
    public void importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		/*try {
            String fileName = "专家信息数据导入模板.xlsx";
    		List<ExpertsInfo> list = Lists.newArrayList();
    		new ExportExcel("专家信息", ExpertsInfo.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/zx/expertsInfo/?repage";*/
		
		
		OutputStream outp = null;
        FileInputStream in = null;
        String templeteName = "专家信息数据导入模板.xlsx";
        try {
            String fileName = templeteName; //要下载的模板文件
            if(templeteName!=null){
                if(!templeteName.endsWith(".xlsx")){
                    fileName = templeteName + ".xlsx";
                }
            }
           
            String ctxPath = getClass().getResource("/templates/excel/" + fileName).getPath();

            String filedownload = ctxPath;
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 要下载的模板所在的绝对路径
            response.reset();
            response.addHeader("Content-Disposition", "attachment; filename="+fileName);
            response.setContentType("application/octet-stream;charset=UTF-8");
            outp = response.getOutputStream();
            in = new FileInputStream(filedownload);
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) > 0) {
                outp.write(b, 0, i);
            }
            outp.flush();
        } catch (Exception e) {
            System.out.println("Error!");
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
                in = null;
            }
            if (outp != null) {
                try {
					outp.close();
				} catch (IOException e) {			
					e.printStackTrace();
				}
                outp = null;
            }
        }

    }
}